package com.qing.reflection;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

/**
 * 性能对比
 */
public class TestTime {
    //普通方式创建
    public static void test01() {
        User user = new User();
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            user.getName();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("普通new创建对象耗时：" + (endTime - startTime) + "ms(毫秒)");
    }

    //反射方式创建
    public static void test02() throws Exception {
        Class c1 = Class.forName("com.qing.reflection.User");
        User user = (User) c1.newInstance();
        Method name = c1.getMethod("getName");
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            name.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式创建对象耗时：" + (endTime - startTime) + "ms(毫秒)");
    }

    //反射方式创建，关闭检测
    public static void test03() throws Exception {
        Class c1 = Class.forName("com.qing.reflection.User");
        User user = (User) c1.newInstance();
        Method name = c1.getMethod("getName");
        name.setAccessible(true);
        long startTime = System.currentTimeMillis();
        for (int i = 0; i < 10_0000_0000; i++) {
            name.invoke(user, null);
        }
        long endTime = System.currentTimeMillis();
        System.out.println("反射方式创建对象，关闭检测耗时：" + (endTime - startTime) + "ms(毫秒)");
    }

    public static void main(String[] args) throws Exception {
        test01();
        test02();
        test03();
    }
}
